// pages/medetail/sale/sale.js
import {imguploadapi,salesapi,aftersalesapi} from "../../../utils/api"
import utils from "../../../utils/util"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        reason:"点击选择申请原因",//原因的默认状态
        reasonid:"",//原因的id
        reasondata:false,//原因的弹出状态
        reasoncolumns: [],//原因的数据
        type:"点击选择申请类型",//类型的默认数据
        typedata:false,//类型的弹出框
        typecolumns: [],//类型数据
        fileList: [],//页面展示的图片数组
        imgarr:[],//提交后台的图片数组
        order_id:"",//订单的id
        salesdata:{},//对应商品的数据
        price:"",//申请的价格
        content:"",//描述
        phone:"",//电话号码
        salesid:"",//申请原因要用的id
        window_heigt: '', //屏幕高
        window_width: '', //屏幕宽
        canv: {
          width: '', //canvas宽
          height: '', //canvas高
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
   async onLoad(options) {
       console.log(options);
       this.setData({
        salesdata:JSON.parse(options.obj),
        order_id:options.orderid
        })
       const res = await salesapi({id:"",order_id:options.orderid,goods_sku_id:JSON.parse(options.obj).goods_sku_id})
       if(res.data.code==200){
           console.log(res.data.data);
           this.setData({
            typecolumns:res.data.data.data,
            price:res.data.data.after_sales_price
           })
           console.log(res.data.data.data);
       }else{
        utils.wxshowtoast("数据请求失败")
       }
    },

    //类型选择确定和申请原因的数据请求
    async typeConfirm(event) {
        const {value, index } = event.detail;
        if(event.type=="confirm"){
            this.setData({
                typedata:false,
                type:value.name,
                salesid:value.id
            })
            // 申请原因数据
            const res = await salesapi({id:this.data.salesid,order_id:this.data.order_id,goods_sku_id:this.data.salesdata.goods_sku_id})
            if(res.data.code==200){
                console.log(res.data.data);
                this.setData({
                 reasoncolumns:res.data.data.data
                })
                 console.log(res.data.data.data);
            }else{
             utils.wxshowtoast("数据请求失败")
            }
        }else{
            this.setData({
                typedata:false
            })
        }
        console.log(`当前值：${value.name}, 当前索引：${index}`,);
    },
    typeClose(){
        this.setData({
            typedata:false
        })
    },
   // 申请类型的选中确定
    typeshow(){
        this.setData({
            typedata:true
        })
    },
    // 售后的描述
    slaesfn(e){
        console.log(e.detail.value);
        var addressreg = /^[^ ]/
        addressreg.test(e.detail.value)?utils.wxshowtoast("描述输入正确的"):utils.wxshowtoast("输入正确的描述")
        this.setData({
            content:e.detail.value
        })
    },
    // 联系电话号码
    phonefn(e){
        var phonereg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])[0-9]{8}$/
        phonereg.test(e.detail.value)? utils.wxshowtoast("手机号输入正确"):utils.wxshowtoast("请输入正确的手机号")
        this.setData({
            phone:e.detail.value
        })
    },
    // 售后的提交
   async salebtn(){
        var addressreg = /^[^ ]/
        var phonereg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])[0-9]{8}$/
        if(this.data.reasonid == ""){
            utils.wxshowtoast("请选择申请类型和申请原因")
            return
        }
        if(this.data.content=="" || !addressreg.test(this.data.content)){
            return utils.wxshowtoast("输入正确的描述")
         }
         if(this.data.phone=="" || !phonereg.test(this.data.phone)){
            return utils.wxshowtoast("输入正确的手机号码")
         }
         console.log(this.data.imgarr);
         const res =await aftersalesapi({
            order_id:this.data.order_id,
            goods_sku_id:this.data.salesdata.goods_sku_id,
            after_sales_id:this.data.reasonid,
            after_sales_price:this.data.price,
            after_sales_imgs:this.data.imgarr,
            after_sales_phone:this.data.phone,
            after_sales_content:this.data.content
         })
         wx.hideLoading()
         if(res.data.code===200){
              console.log(res.data.data);
              wx.redirectTo({
                url: '/pages/medetail/meorder/meorder?id=0'
              })
         }else{
             utils.wxshowtoast("提交失败")
         }
    },
    //申请原因
    reasonConfirm(event) {
        const {value, index } = event.detail;
        if(event.type=="confirm"){
            this.setData({
                reasondata:false,
                reason:value.name,
                reasonid:value.id
            })
        }else{
            this.setData({
                reasondata:false
            })
        }
        console.log(`当前值：${value}, 当前索引：${index}`,);
    },
    reasonClose(){
        this.setData({
            reasondata:false
        })
    },
    reasonshow(){
        if(this.data.salesid==""){
          return utils.wxshowtoast("请先选择申请类型")
        }
        this.setData({
            reasondata:true
        })
    },
    
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        var that = this;
        wx.getSystemInfo({
        success: function (res) {
            //获取屏幕窗口高度和宽度
            console.log(res);
            that.data.window_heigt = res.windowHeight
            that.data.window_width = res.windowWidth
        },
        })
    },
    _addImg() {
        var that = this;
        console.log(this.data.fileList.length)
        if (this.data.fileList.length==5) {
            return utils.wxshowtoast('最多5张图片')
        }
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
            sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
            success: res => {
            that.data.fileList= that.data.fileList.concat(res.tempFiles)
            that.setData({ 
            fileList: that.data.fileList
            });
            console.log(res.tempFilePaths);
            that.getCanvasImg(res.tempFilePaths)
            }
        })
      },
      //压缩并获取图片
  getCanvasImg:function (tempFilePaths) {
    var that = this
    wx.showLoading();
    wx.getImageInfo({
      src: tempFilePaths[0], //图片的路径，可以是相对路径，临时文件路径，存储文件路径，网络图片路径,  
      success: res => {
        console.log(res);
        that.data.canv.width = that.data.window_width;
        that.data.canv.height = that.data.window_width / res.width * res.height;
        that.setData({
          canv: that.data.canv
        })
        console.log(this.data.canv);
        const ctx = wx.createCanvasContext('attendCanvasId');
        setTimeout(() => {
          ctx.drawImage(tempFilePaths[0], 0, 0, that.data.canv.width, that.data.canv.height);
          ctx.draw(true, function () {
            wx.canvasToTempFilePath({
              canvasId: 'attendCanvasId',
              fileType:"jpg",
              success: function (res) {
               wx.hideLoading();
               that.uploadFile(res.tempFilePath)
              },
              fail: function (e) {
                that.getCanvasImg(tempFilePaths);
              }
            });
          });
        }, 1000);
      },
      fail: () => {},
      complete: () => {}
    });
  },
      async uploadFile(star){
        const res =await imguploadapi(star)
        wx.hideLoading()
        this.data.imgarr.push(JSON.parse(res.data).data.url)
        this.setData({
            imgarr:this.data.imgarr
        })
      },
      //点击进行图片删除
      _onDelTab(e) {
        // 获取图片索引
        let idx = e.currentTarget.dataset.idx;
        this.data.fileList.splice(idx, 1);
        this.data.imgarr.splice(idx, 1);
        this.setData({
          fileList: this.data.fileList,
          imgarr:this.data.imgarr
        })
      },
    
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})